<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
import { queryDataRateInSimilarType } from '@/api/front/fund/fundDataContent'
import { formatDateTime } from '@/views/front/detail/components/grandTotal/fomatDateTime'

const animationDuration = 1000

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '500px'
    },
    codeNumber: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null,
      chartData: [],
      legendData: [],
      xData: [],
      seriesData: []
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    // 初始化 Echarts
    initChart() {
      // 初始化 chart
      this.chart = echarts.init(this.$el)

      // 获取数据
      queryDataRateInSimilarType(this.codeNumber).then(res => {
        this.xData = res.map(item => { return formatDateTime(item.x) })
        const seriesData1 = res.map(item => { return Number(item.y) })
        this.seriesData.push(seriesData1)
        // chartData = [ [legendData],[xData],[seriesData1] ]
        // chart 数据渲染
        this.setChartOption()
      })
    },

    // 设置 Echarts option
    setChartOption() {
      this.chart.setOption({
        title: {
          left: 'center',
          text: '同类排名走势'
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          // bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.xData
        },
        yAxis: {
          type: 'value'
        },
        dataZoom: [{
          type: 'inside',
          start: 98,
          end: 100
        }, {
          start: 98,
          end: 100
        }],
        series: [
          {
            name: '同类排名走势',
            type: 'line',
            // stack: '总量',
            data: this.seriesData[0]
          }
        ],
        animationDuration
      })
    },

    // 重设大小
    resizeChart() {
      this.chart.resize()
    }
  }
}
</script>
